package com.jx.driving.util;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * 
 * @author wuxiaozeng
 *
 */
public class ClassUtils {

    /**
     * 使用反射根据属性名称获取属性值
     * 
     * @param fieldName 属性名称
     * @param o 操作对象
     * @return Object 属性值
     */
    public static Object getFieldValueByName(String fieldName, Object o) {
	try {
	    String firstLetter = fieldName.substring(0, 1).toUpperCase();
	    String getter = "get" + firstLetter + fieldName.substring(1);
	    List<Method> methods = getMothds(o.getClass(), true);
	    for (Method method : methods) {
		if (method.getName().equals(getter)) {
		    Object value = method.invoke(o, new Object[] {});
		    return value;
		}
	    }
	    return null;
	} catch (Exception e) {
	    e.printStackTrace();
	}
	return null;
    }

    /**
     * 获取类实例的方法
     * 
     * @param clazz 类名
     * @param includeParentClass 是否包括父类的方法
     * @return List
     */
    public static List<Method> getMothds(Class clazz, boolean includeParentClass) {
	List<Method> list = new ArrayList<Method>();
	Method[] methods = clazz.getDeclaredMethods();
	for (Method method : methods) {
	    list.add(method);
	}
	if (includeParentClass && clazz.getSuperclass() != null) {
	    getParentClassMothds(list, clazz.getSuperclass());
	}
	return list;
    }

    /**
     * 获取类实例的父类的方法
     */
    private static List<Method> getParentClassMothds(List<Method> list, Class clazz) {
	Method[] methods = clazz.getDeclaredMethods();
	for (Method method : methods) {
	    list.add(method);
	}
	if (clazz.getSuperclass() == Object.class) {
	    return list;
	}
	if (clazz.getSuperclass() != null) {
	    getParentClassMothds(list, clazz.getSuperclass());
	}
	return list;
    }

    /**
     * 获取类实例的属性
     */
    public static List<Field> getClassFields(Class clazz, boolean includeParentClass) {
	List<Field> listFields = new ArrayList<Field>();
	Field[] fields = clazz.getDeclaredFields();
	for (Field field : fields) {
	    listFields.add(field);
	}
	if (includeParentClass) {
	    getParentClassFields(listFields, clazz.getSuperclass());
	}
	return listFields;
    }

    /**
     * 获取类实例的父类的属性值
     */
    private static List<Field> getParentClassFields(List<Field> fields, Class clazz) {
	Field[] parentFields = clazz.getDeclaredFields();
	for (Field field : parentFields) {
	    fields.add(field);
	}
	if (clazz.getSuperclass() == null) {
	    return fields;
	}
	getParentClassFields(fields, clazz.getSuperclass());
	return fields;
    }

}
